package com.liukai.bishe.ui.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.liukai.bishe.utils.ToastUtil;

import java.util.Random;

public class CountDownService extends Service {

    private static final String TAG = "CountDownService";

    private Random mGenerator;
    private IBinder mIBinder;
    private int mTime;
    private Thread mThread;

    public class MyBinder extends Binder {
        public CountDownService getService() {
            return CountDownService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mIBinder = new MyBinder();
        mThread = new Thread(() -> {
            while (mTime > 0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mTime --;
                Intent intent1=new Intent();
                intent1.putExtra("time", mTime);
                intent1.setAction("com.liukai.bishe.ui.service.CountDownService");
                sendBroadcast(intent1);
                ToastUtil.log("Service============>","time",mTime+"");
            }
        });
    }

    public CountDownService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
//        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return mIBinder;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "==========================>onDestroy");
        mTime = 0;
        mThread.interrupt();
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "==============================>onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.e(TAG, "onRebind");
        super.onRebind(intent);
    }

    public int getRandomNumber() {
        return mGenerator.nextInt(100);
    }

    /**
     * 启动服务开启倒计时
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String timeString = intent.getStringExtra("time");
        mTime = Integer.parseInt(timeString);


        mThread.start();

//        new Thread(() -> {
//
//        }).start();

        return super.onStartCommand(intent, flags, startId);
    }
}
